package arcane.object.gui.specific;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.AdjustmentEvent;

import arcane.object.gui.BevelBorder;
import arcane.object.gui.scroll.ScrollBar;
import arcane.object.gui.scroll.ScrollPanel;

public class ChatDisplayArea extends ScrollPanel<String> {
	Color bgColor;
	int gap = 2;

	protected int maxHistory;

	public ChatDisplayArea(int x, int y, int w, int h) {
		super(x, y, w, h);
		bgColor = new Color(1f, 0f, 0f, .2f);
		setBorder(new BevelBorder(BevelBorder.BEVEL_UP));
		maxHistory = 100;
	}

	public int getLastSpace(String words) {
		char[] ary = words.toCharArray();
		char space = ' ';
		for (int i = ary.length - 1; i > -1; i--) {
			if (ary[i] == space)
				return i;
		}
		return -1;
	}

	/**
	 * Adds a string to be displayed within this display area.
	 * 
	 * @param words
	 *            words to be added
	 */
	public void add(String words) {
		int totLines = 0;
		int index = words.indexOf(':');
		String name = words.substring(0, index + 2);
		words = words.substring(index + 2);
		int width = font.getWidth(name);
		int spaceWidth = font.getWidth(' ');
		for (int i = 0; i < words.length(); i++) {
			width += font.getWidth(words.charAt(i));
			// Have exceeded display size
			if (width > this.width - 10) {
				// make room for indent if not on 1st line
				if (totLines != 0) {
					width += spaceWidth;
					i -= 2;
				} else {
					--i;
				}
				String sub1 = words.substring(0, i);
				// try to get last occurring space
				int lastSpace = getLastSpace(sub1);
				// last occurring space is valid
				if (lastSpace > -1) {
					super.add(totLines == 0 ? name
							+ words.substring(0, lastSpace) : " "
							+ words.substring(0, lastSpace));
					words = words.substring(lastSpace + 1);
				}
				// There was no last occurring spacer
				else {
					super.add(totLines == 0 ? name + sub1 : " " + sub1);
					words = words.substring(i);
				}
				++totLines;
				i = width = 0;
			}
		}
		// Add any leftover words that didn't exceed width of display
		if (words.length() != 0) {
			super.add(totLines == 0 ? name + words : " " + words);
		}
		while(size()>maxHistory)
			remove(0);
			
		//Scroll to bottom if data is entered
		int value = calculateVerticalArea() - height;
		if (value > 0)
			visibleY = value;
	}
}